const jwt = require('jsonwebtoken');
const RedisManager = require('../utils/RedisManager');

//TODO 把KEY放到config下
const KEY = "#&*(&(*jfsfj77888****a";
const two_days = 172800

const setUserToken = (id, roles, infoId) =>{
    return new Promise((resolve, reject) => {
			const exp = Math.floor(Date.now() / 1000) + (60 * 60);
			const data = {id: id, roles: roles, infoId: infoId};
			jwt.sign({exp, data}, KEY, {}, (err, token) => {
				if (err != null) {
					return reject(err)
				} 
				RedisManager.set('token/' + id.toString(), token, 'EX', two_days, err => {
					 if(err == null) {
							 resolve(token)
					 } else {
							console.log(err)
							 reject(err)
					 }
				})
			});
    })
};



const getToken = id => {
    return new Promise((resolve, reject) => {
        RedisManager.get('token/' + id, (err, reply) => {
            if (err) {
                console.log('errr');
								resolve(null)
            } else {
                resolve(reply);
            }
        });
    });
};

const removeToken = id => {
    return new Promise((resolve, reject) => {
        RedisManager.del('token/' + id, (err, reply) => {
            if (err) {
                console.log('errr');
								resolve(null)
            } else {
                resolve(reply);
            }
        });
    });
};

const decodeToken = token => {
	return new Promise((resolve, reject) => {
		jwt.verify(token, KEY, (err, accountInfo) => {
			if (err != null) {
				console.log("token expire")
				resolve(null)
			} else {
				if(accountInfo.data.id) {
					resolve(accountInfo.data)
				} else {
					resolve(null)
				}
			}
		});
	})
}



//TODO 暴露方法
module.exports = {
	setUserToken,
	getToken,
	decodeToken,
	removeToken,
}

